package com.xyz.frame.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xyz.frame.bean.model.Weight;
import com.xyz.frame.bean.vo.WeightListVO;
import com.xyz.frame.dao.WeightMapper;
import com.xyz.frame.service.WeightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class WeightServiceImpl implements WeightService {
    @Autowired
    private WeightMapper weightMapper;

    @Override
    public void add(Weight weight) {
        weightMapper.insert(weight);
    }

    @Override
    public void update(Weight weight) {
        weightMapper.updateById(weight);
    }

    @Override
    public Weight getWeight(String userId, Date submitDate) {
        QueryWrapper<Weight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("submit_date", submitDate);
        return weightMapper.selectOne(queryWrapper);
    }

    @Override
    public List<WeightListVO> getWeightList(Date startDate, Date endDate, String userId) {
        LambdaQueryWrapper<Weight> qw = new LambdaQueryWrapper<>();
        Optional.ofNullable(startDate).ifPresent(
                date -> qw.ge(Weight::getSubmitDate, date));
        Optional.ofNullable(endDate).ifPresent(
                date -> qw.le(Weight::getSubmitDate, date));
        List<Weight> weights = weightMapper.selectList(qw);
        List<WeightListVO> weightList = new ArrayList<>();
        weights.forEach((weight -> {
            if (userId.equals(weight.getUserId())){
                WeightListVO weightListVO = new WeightListVO();
                weightListVO.setWeight(weight.getWeight());
                // 定义日期格式
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String submitDate = dateFormat.format(weight.getSubmitDate());

                weightListVO.setSubmitDate(submitDate);
                weightList.add(weightListVO);
            }
        }));
        return weightList;
    }
}
